package com.traffic.between.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.RongJingSignUtil;

public class RongJingServiceImpl {
	
	private static final String ENCODE = "UTF-8";// 相关编码

	private static SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmss");

	// 开发
	 private static String SecretKey =  BetweenProperties.RONGJING_SECRETKEY;//"188790835119FFA3729E76864A33961E";
	 private static String callUrl =  BetweenProperties.RONGJING_ORDER_URL;//"http://123.56.92.132:20003/FlowManager/";
	 private static String cp_id = BetweenProperties.RONGJING_CPID;//"52";
    
	 private static Logger logger = Logger.getLogger(RongJingServiceImpl.class);
	 public static RongJingServiceImpl service = new RongJingServiceImpl();

	public String order(String pkgNo, String phoneNo, String tradeNo,String region) {
		String result = "";
		String datestr = SDF.format(new Date());
		JSONObject paramJson = new JSONObject();
		// 订购相关参数
		paramJson.put("cp_id", cp_id);
		paramJson.put("flow",pkgNo);
		paramJson.put("prorange",region);//流量的使用范围0全国1省内
		paramJson.put("belong",region);//流量包归属地0全国1省内
		paramJson.put("usermobile",phoneNo);
		Map<String, String> signatureMap = new HashMap<String, String>();
		signatureMap.put("cp_id", cp_id); // 接口分配
		signatureMap.put("SecretKey", SecretKey); // 接口分配，不参与排序
		signatureMap.put("method", "orderflow"); // 请求结果参数
		signatureMap.put("timestamp", datestr); // 请求结果参数
		if (callUrl.indexOf("orderflow?") < 0) {
			callUrl += "orderflow?";
		}
		
		String url = getUrl(jsonToMapString(paramJson.toString()), signatureMap, callUrl);

	    logger.info("北京荣景订购请求参数："+paramJson.toString());
		CloseableHttpClient client = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity reqEntity = new StringEntity(paramJson.toString(), ENCODE);
			reqEntity.setContentType("text/plain; charset=utf-8;");
			reqEntity.setContentEncoding(ENCODE);
			httpPost.setEntity(reqEntity);
			HttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity,"utf-8");
            logger.info("北京荣景订购请求返回参数："+result);
		} catch (Exception e) {
			logger.info("北京荣景订购请求异常："+e.getMessage());
		
		}
		
        return result;
	}
	
	/* 对外接口使用获得返回的json字符串 */
	public static String getUrl(Map<String, String> parameterMap,
			Map<String, String> signatureMap, String visitUrl) {
		// 获得签名字符串
		String sign = mapToRessignVerify(parameterMap, signatureMap);
		signatureMap.put("sign", sign);
		String parameter = getUrlParameter(signatureMap);// 获得参数的字符串
		return visitUrl + parameter;// 获得总的访问路径
	}
	
	/**
	 * 获得签名串sign SIGN 加密
	 * 
	 * @param params
	 *            消息体字符串
	 * @param busiId
	 *            业务ID
	 * @param method
	 *            业务方法
	 * @param timestamp
	 *            时间戳
	 * @param sign
	 *            密钥SK
	 * @return
	 */
	// 将相关的参数转为签名串
	public static String mapToRessignVerify(Map<String, String> parameterMap,
			Map<String, String> signatureMap) {
		String parameterString = JSONObject.fromObject(parameterMap).toString();
		return stringToRessignVerify(parameterString, signatureMap);
	}
	
	/* 对map的key值进行排序 */

	/* 获得参数的字符串 */
	public static String getUrlParameter(Map<String, String> map) {
		String parameter = "";
		map.remove("SecretKey");
		for (Map.Entry<String, String> entity : map.entrySet()) {
			if (entity.getKey().equals("sign")) {
				parameter = parameter + "&" + entity.getKey() + "="
						+ entity.getValue();
			} else {
				parameter = entity.getKey() + "=" + entity.getValue() + "&"
						+ parameter;
			}
		}
		return parameter.replace("&&", "&");
	}

	
	// 将相关的参数转为签名串
		public static String stringToRessignVerify(String paramStr,
				Map<String, String> signatureMap) {
			String secretKey = signatureMap.get("SecretKey");
			signatureMap.remove("SecretKey");
			JSONObject  para = JSONObject.fromObject(paramStr);
			List<Map.Entry<String, String>> list = mapKeySort(signatureMap);
			String param = list.toString().replace("[", "").replace("]", "")
					.replaceAll("=", "").replaceAll(",", "").replaceAll(" ", "");
			return RongJingSignUtil.md5Digest(secretKey + param + para + secretKey);
		}
		
		public static Map<String, String> jsonToMapString(String json) {
			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, String> map = new HashMap<String, String>();
			try {
				// 将json字符串转成map结合解析出来，并打印(这里以解析成map为例)
				map = objectMapper.readValue(json, Map.class);
				
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return map;
		}
		
		public static String mapToJson(Map map) {
			JSONObject jsObj = JSONObject.fromObject(map);
			return jsObj.toString();
		}


		public static List<Map.Entry<String,String>> mapKeySort(Map<String, String> map) {
			// 通过ArrayList构造函数把map.entrySet()转换成list
			List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
			// 通过比较器实现比较排序
			Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
				public int compare(Map.Entry<String, String> o1,
						Map.Entry<String, String> o2) {
					return o1.getKey().compareTo (o2.getKey()); //升序
//					return o2.getKey().compareTo(o1.getKey()); // 倒序
				}
			});
			return list;
		}
       public static void main(String[] args) {
		new RongJingServiceImpl().order("", "", "", "");
	}
}
